class Card {
    constructor(value, suit) {
        this.value = value;
        this.suit = suit;
        this.isSelected = false;
    }

    get attack() {
        return this.value;
    }

    get isJoker() {
        return false;
    }

    toString() {
        const suits = {
            'hearts': '♥️',
            'diamonds': '♦️',
            'clubs': '♣️',
            'spades': '♠️'
        };
        const values = {
            1: 'A',
            11: 'J',
            12: 'Q',
            13: 'K'
        };
        return `${suits[this.suit]}${values[this.value] || this.value}`;
    }
}

class Boss extends Card {
    constructor(value, suit) {
        super(value, suit);
        this.maxHealth = this.getMaxHealth();
        this.health = this.maxHealth;
        this.baseAttack = this.getBaseAttack();
        this.currentAttack = this.baseAttack;
    }

    getMaxHealth() {
        switch(this.value) {
            case 11: return 20; // J
            case 12: return 30; // Q
            case 13: return 40; // K
            default: return 0;
        }
    }

    getBaseAttack() {
        switch(this.value) {
            case 11: return 10; // J
            case 12: return 15; // Q
            case 13: return 20; // K
            default: return 0;
        }
    }

    takeDamage(amount) {
        this.health -= amount;
        return this.health <= 0;
    }

    resetAttack() {
        this.currentAttack = this.baseAttack;
    }

    reduceAttack(amount) {
        this.currentAttack = Math.max(0, this.currentAttack - amount);
    }
}

class GameManager {
    constructor() {
        this.deck = [];
        this.hand = [];
        this.discardPile = [];
        this.currentBoss = null;
        this.bossDeck = [];
        this.selectedCards = [];
        this.maxHandSize = 8; // 单人模式下的手牌上限

        this.initializeGame();
        this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
        this.loadSoundEffects();
    }

    loadSoundEffects() {
        this.sounds = {
            cardPlay: this.createAudioBuffer(0.1, 220),  // 出牌音效
            cardSelect: this.createAudioBuffer(0.05, 440), // 选牌音效
            damage: this.createAudioBuffer(0.15, 110),    // 伤害音效
            victory: this.createAudioBuffer(0.3, 880)     // 胜利音效
        };
    }

    createAudioBuffer(duration, frequency) {
        const sampleRate = this.audioContext.sampleRate;
        const buffer = this.audioContext.createBuffer(1, duration * sampleRate, sampleRate);
        const data = buffer.getChannelData(0);
        for (let i = 0; i < buffer.length; i++) {
            data[i] = Math.sin(2 * Math.PI * frequency * i / sampleRate);
        }
        return buffer;
    }

    playSound(soundName) {
        const source = this.audioContext.createBufferSource();
        source.buffer = this.sounds[soundName];
        source.connect(this.audioContext.destination);
        source.start();
    }

    initializeGame() {
        // 初始化普通卡牌（1-10）
        const suits = ['hearts', 'diamonds', 'clubs', 'spades'];
        for (let suit of suits) {
            for (let value = 1; value <= 10; value++) {
                this.deck.push(new Card(value, suit));
            }
        }

        // 初始化Boss卡牌（J、Q、K）
        for (let suit of suits) {
            for (let value = 11; value <= 13; value++) {
                this.bossDeck.push(new Boss(value, suit));
            }
        }

        this.shuffleDeck();
        this.shuffleBossDeck();
        this.drawInitialHand();
        this.nextBoss();
    }

    shuffleDeck() {
        for (let i = this.deck.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this.deck[i], this.deck[j]] = [this.deck[j], this.deck[i]];
        }
    }

    shuffleBossDeck() {
        // 按J-Q-K的顺序排列
        this.bossDeck.sort((a, b) => a.value - b.value);
    }

    drawInitialHand() {
        while (this.hand.length < this.maxHandSize && this.deck.length > 0) {
            this.hand.push(this.deck.pop());
        }
    }

    nextBoss() {
        if (this.bossDeck.length > 0) {
            this.currentBoss = this.bossDeck.shift();
            return true;
        }
        return false;
    }

    selectCard(index) {
        const card = this.hand[index];
        if (!card) return false;

        if (card.isSelected) {
            card.isSelected = false;
            this.selectedCards = this.selectedCards.filter(c => c !== card);
        } else {
            card.isSelected = true;
            this.selectedCards.push(card);
        }
        this.playSound('cardSelect');
        return true;
    }

    playSelectedCards() {
        if (!this.canPlaySelectedCards()) return false;
        this.playSound('cardPlay');

        let damage = 0;
        let isDoubled = false;

        // 计算伤害和触发效果
        for (const card of this.selectedCards) {
            damage += card.attack;

            // 检查花色效果
            if (card.suit !== this.currentBoss.suit) {
                switch (card.suit) {
                    case 'hearts':
                        // 从弃牌堆回收牌
                        for (let i = 0; i < card.value && this.discardPile.length > 0; i++) {
                            this.deck.unshift(this.discardPile.pop());
                        }
                        break;
                    case 'diamonds':
                        // 抽牌
                        for (let i = 0; i < card.value && this.deck.length > 0; i++) {
                            if (this.hand.length < this.maxHandSize) {
                                this.hand.push(this.deck.pop());
                            }
                        }
                        break;
                    case 'clubs':
                        // 伤害翻倍
                        isDoubled = true;
                        break;
                    case 'spades':
                        // 减少Boss攻击力
                        this.currentBoss.reduceAttack(card.value);
                        break;
                }
            }
        }

        // 应用伤害
        if (isDoubled) damage *= 2;
        const isBossDefeated = this.currentBoss.takeDamage(damage);

        // 将打出的牌移到弃牌堆
        this.discardPile.push(...this.selectedCards);
        this.hand = this.hand.filter(card => !this.selectedCards.includes(card));
        this.selectedCards = [];

        // 如果Boss被击败，检查是否需要将其加入牌组
        if (isBossDefeated) {
            if (this.currentBoss.health === 0) {
                // 精确击杀，将Boss加入牌组顶部
                this.deck.push(this.currentBoss);
            }
            this.nextBoss();
            this.playSound('victory');
        } else {
            this.playSound('damage');
        }

        return true;
    }

    skipTurn() {
        // 玩家选择跳过回合
        return this.currentBoss.currentAttack === 0;
    }

    discardForDamage() {
        // 玩家需要弃掉足够的牌来抵挡Boss的攻击
        const requiredValue = this.currentBoss.currentAttack;
        const validCards = this.hand.filter(card => card.value >= requiredValue);
        return validCards.length > 0;
    }
}

// 初始化游戏
const game = new GameManager();

// DOM 操作
function updateGameState() {
    // 更新Boss区域
    const bossArea = document.getElementById('bossArea');
    if (game.currentBoss) {
        bossArea.innerHTML = `
            <h2>${game.currentBoss.toString()}</h2>
            <p>生命值: ${game.currentBoss.health}/${game.currentBoss.maxHealth}</p>
            <p>攻击力: ${game.currentBoss.currentAttack}</p>
        `;
    } else {
        bossArea.innerHTML = '<h2>胜利！</h2>';
    }

    // 更新玩家手牌
    const playerHand = document.getElementById('playerHand');
    playerHand.innerHTML = game.hand.map((card, index) => `
        <div class="card ${card.isSelected ? 'selected' : ''}" 
             onclick="handleCardClick(${index})">
            ${card.toString()}
        </div>
    `).join('');

    // 更新按钮状态
    document.getElementById('playCardBtn').disabled = !game.canPlaySelectedCards();
    document.getElementById('skipTurnBtn').disabled = game.currentBoss.currentAttack > 0;
}

// 事件处理
function handleCardClick(index) {
    game.selectCard(index);
    updateGameState();
}

document.getElementById('playCardBtn').addEventListener('click', () => {
    if (game.playSelectedCards()) {
        updateGameState();
    }
});

document.getElementById('skipTurnBtn').addEventListener('click', () => {
    if (game.skipTurn()) {
        updateGameState();
    }
});

// 初始化游戏界面
updateGameState();